package com.ocelot.san.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ocelot.san.dto.Role;
import com.ocelot.san.dto.User;

public class UserDetailsSecurityService implements UserDetailsService {

	@Resource
	UserService userService;

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        User user = userService.findById(username);
        if (user == null)
            throw new UsernameNotFoundException("User not found: " + username);
        else {
            return makeUser(user);
        }
    }

    private org.springframework.security.core.userdetails.User makeUser(User user) {
        return new org.springframework.security.core.userdetails.User(user.getLogin(), user
                .getPassword(), makeGrantedAuthorities(user));
    }

    private List<GrantedAuthority> makeGrantedAuthorities(User user) {
        List<GrantedAuthority>result = new ArrayList<GrantedAuthority>();
        for (Role role : user.getRoles()) {
            result.add(new SimpleGrantedAuthority(role.getName()));
        }
        return result;
    }

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
